﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Web.Mvc;

using VehicleManagement.Codes;
using VehicleManagement.Models;
using VehicleManagement.ControllersServices;


namespace VehicleManagement.Controllers
{
    
    /// <summary>
    /// 用户登录控制类
    /// </summary>
    public class HomeController : Controller
    {
        public static string userRole = "";

        //
        // GET: /Home/

        /// <summary>
        /// 宣传页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Home/Login

        /// <summary>
        /// 进入登录界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 点击登录后判断用户类型，登录系统
        /// </summary>
        /// <param name="user">用户信息对象（用户类型、用户名和密码）</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(UserLogin user)
        {
            if (Request.RequestType.ToUpper().Equals("POST") && user != null)
            {
                if (user.UserType.Equals("管理员"))
                {
                    AdminLogin(user.UserName.Trim(), user.UserPassword.Trim());
                }
                else if (user.UserType.Equals("申请人"))
                {
                    ApplicantLogin(user.UserName.Trim(), user.UserPassword.Trim());
                }
                else if (user.UserType.Equals("负责人"))
                {
                    DriverManagerLogin(user.UserName.Trim(), user.UserPassword.Trim());
                }
                else if (user.UserType.Equals("财务人员"))
                {
                    FinanceManagerLogin(user.UserName.Trim(), user.UserPassword.Trim());
                }
                else if (user.UserType.Equals("司机"))
                {
                    //司机
                    return View("Login");
                }
            }
            
            return View("Login");

        }

        /// <summary>
        /// 点击登录后判断用户类型，登录系统
        /// </summary>
        /// <param name="user">用户信息对象（用户类型、用户名和密码）</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UsersLogin(string UserType, string UserName, string UserPassword)
        {
            //if (Request.RequestType.ToUpper().Equals("POST"))

                if (UserType.Equals("管理员"))
                {
                    if (!AdminLogin(UserName.Trim(), UserPassword.Trim()))
                    {
                        return Json(new { Result = "false", Message = "用户名或密码不正确" });
                    }
                }
                else if (UserType.Equals("申请人"))
                {
                    if (ApplicantLogin(UserName.Trim(), UserPassword.Trim()))
                    {
                        return Json(new { Result = "false", Message = "用户名或密码不正确" });
                    }
                }
                else if (UserType.Equals("负责人"))
                {
                    if (DriverManagerLogin(UserName.Trim(), UserPassword.Trim()))
                    {
                        return Json(new { Result = "false", Message = "用户名或密码不正确" });
                    }
                }
                else if (UserType.Equals("财务人员"))
                {
                    if (FinanceManagerLogin(UserName.Trim(), UserPassword.Trim()))
                    {
                        return Json(new { Result = "false", Message = "用户名或密码不正确" });
                    }
                }
                else if (UserType.Equals("司机"))
                {
                    //司机
                    return View("Login");
                }

            return View("Login");

        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="admim"> 管理员信息对象（用户名和密码）</param>
        /// <returns></returns>
        [NonAction]
        private bool AdminLogin(string adminName, string adminPassword)
        {
            Hashtable ht = new Hashtable();
            ht.Add("adminName", adminName);
            ht.Add("adminPassword", adminPassword);

            int count = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_COUNT_ADMIN", ht));

            if (count <= 0)
            {
                //Response.Write("<script language='javascript'>alert('用户名或密码不正确!');</script>");
                ViewBag.LoginErrorMessage = "用户名或密码不正确!";
                return false;
            }
            else
            {
                int adminID = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_ADMIN_ID", adminName));
                Session["UserID"] = adminID;
                Session["AdminID"] = adminID;
                userRole = "管理员";
                Response.Redirect("../Applicant/Index");
                return true;

            }
        }

        /// <summary>
        /// 申请人登录
        /// </summary>
        /// <param name="admim"> 申请人信息对象（用户名和密码）</param>
        /// <returns></returns>
        [NonAction]
        private bool ApplicantLogin(string applicantName, string applicantPassword)
        {

            Hashtable ht = new Hashtable();
            ht.Add("applicantName", applicantName);
            ht.Add("applicantPassword", applicantPassword);

            int count = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_COUNT_APPLICANT", ht));

            if (count <= 0)
            {
                //Response.Write("<script language='javascript'>alert('用户名或密码不正确!');</script>");
                ViewBag.LoginErrorMessage = "用户名或密码不正确!";
                return false;
            }
            else
            {
                int applicantID = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_APPLICANT_ID", applicantName));
                Session["UserID"] = applicantID;
                Session["ApplicantID"] = applicantID;
                userRole = "申请人";
                Response.Redirect("../Apply/MyApplys");

            }

            return true;
        }

        /// <summary>
        /// 负责人登录
        /// </summary>
        /// <param name="admim"> 负责人信息对象（用户名和密码）</param>
        /// <returns></returns>
        [NonAction]
        private bool DriverManagerLogin(string driverManagerName, string driverManagerPassword)
        {
            Hashtable ht = new Hashtable();
            ht.Add("driverManagerName", driverManagerName);
            ht.Add("driverManagerPassword", driverManagerPassword);

            int count = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_COUNT_DRIVERMANAGER", ht));

            if (count <= 0)
            {
                //Response.Write("<script language='javascript'>alert('用户名或密码不正确!');</script>");
                ViewBag.LoginErrorMessage = "用户名或密码不正确!";
                return false;
            }
            else
            {
                int driverManagerID = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_DRIVERMANAGER_ID", driverManagerName));
                Session["UserID"] = driverManagerID;
                Session["DriverManagerID"] = driverManagerID;
                userRole = "负责人";
                Response.Redirect("../Driver/Index");

            }

            return true;
        }

        /// <summary>
        /// 财务人员登录
        /// </summary>
        /// <param name="admim"> 财务人员信息对象（用户名和密码）</param>
        /// <returns></returns>
        [NonAction]
        private bool FinanceManagerLogin(string financeManagerName, string financeManagerPassword)
        {
            Hashtable ht = new Hashtable();
            ht.Add("financeManagerName", financeManagerName);
            ht.Add("financeManagerPassword", financeManagerPassword);

            int count = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_COUNT_FINANCEOFFICER", ht));

            if (count <= 0)
            {
                //Response.Write("<script language='javascript'>alert('用户名或密码不正确!');</script>");
                ViewBag.LoginErrorMessage = "用户名或密码不正确!";
                return false;
            }
            else
            {
                int financeOfficerID = Convert.ToInt32(SqlMapperManager.Instance.Get().QueryForObject("SELECT_FINANCEOFFICER_ID", financeManagerName));
                Session["UserID"] = financeOfficerID;
                Session["FinanceOfficerID"] = financeOfficerID;
                userRole = "财务人员";
                Response.Redirect(string.Format("../FinanManInfo/GetFinanManInfo/{0}", financeOfficerID));

            }

            return true;
        }

        //
        // GET: /Home/Logout

        /// <summary>
        /// 注销账号，退出系统
        /// </summary>
        [HttpPost]
        public void Logout()
        {
            Session["UserID"] = null;

            Session["AdminID"] = null;

            Session["ApplicantID"] = null;

            Session["DriverManagerID"] = null;

            Session["FinanceOfficerID"] = null;
            //司机
            Session["DriverID"] = null;

            userRole = "";
        }
    }

    /// <summary>
    /// 视图访问权限控制类
    /// </summary>
    public class CustomerAuthorizeAttribute : AuthorizeAttribute
    {
        [NonAction]
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            String[] users = Users.Split(','); //取得输入user清单
            String[] roles = Roles.Split(','); //取得输入role清单
            //if (!httpContext.User.Identity.IsAuthenticated)//判断是否已验证
            //    return false;
            if (roles.Length != 0)
            {
                //ASSETEntities db = new ASSETEntities();
                //String account = httpContext.User.Identity.Name.ToString(); //登入的使用者账号
                //bool Isright = false;//角色是否正确
                //var q = from tbl in db.USERPROFILE
                //        where tbl.ACCOUNT == account
                //        select new
                //        {
                //            tbl.ROLE
                //        };
                foreach (String inputRole in roles)//循环比对角色
                {
                    if (HomeController.userRole == inputRole)
                        return true;
                }

                HttpContext.Current.Response.Redirect("/Home/Login", true);

                Logout();

                return false;
            }

            return true;
        }

        public void Logout()
        {

            HttpContext.Current.Session["AdminID"] = null;

            HttpContext.Current.Session["ApplicantID"] = null;

            HttpContext.Current.Session["DriverManagerID"] = null;

            HttpContext.Current.Session["FinanceOfficerID"] = null;
            //司机
            HttpContext.Current.Session["DriverID"] = null;

            HomeController.userRole = "";
        }
    }

}
